from base.shared.JenaException import JenaException

"""
 description 用来描述一个节点
 
    正常有rdf:about
    
    rdf:resource 一般是关联到某个具体的 s p o 中的o
    
    rdf:datatype 指定这个资源的类型是什么 对应某个uri 或者某种类型的简称 xsd:string
    
    rdf:ID  一般是对subject的标记
    
    rdf:li
    
    rdf:_n
    
    rdf:nodeID  一般是对resource的标记
    
    rdf:parseType 指定用什么类型来解析
    
    rdf:RDF root
    
    xml:lang
    
    空节点的表示 
        
        方法一：
            
            rdf:nodeID="abc"
        
        方法二：
            
            <rdf:Description>
            </rdf:Description>

"""


ns = {
        'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
        'rdfs': 'http://www.w3.org/2000/01/rdf-schema#',
        'dc': 'http://purl.org/dc/elements/1.1/'
      }

def pickDescription(elements):
    return elements.findall('rdf:Description', ns)
    # li = []
    # for ele in elements:
    #     print(ele.tag)
    #     if ele.tag == '{' + base + '}' + 'Description':
    #        li.append(ele)
    # return li

def hasRdfAttr(ele, attr):
    key = '{' + ns['rdf'] + '}' + attr
    if ele and ele.attrib and ele.attrib[key]:
        return True

def rdfAttrKey(attr):
    return '{' + ns['rdf'] + '}' + attr

def findNode(descs, nodeID):
    for desc in descs:
        if hasRdfAttr(desc, 'ID') and not hasRdfAttr(desc, 'nodeID') and rdfAttrKey('ID') == nodeID:
            return desc



class Node:

    def __init__(self):
        self.id = None
        self.about = None
        self.propDict = {}

    def addProperty(self, prop, resource):
        self.propDict[prop] = resource
		
class Resource:
	
	def __init__(self):
		self.about = None
		self.datatype = None
		self.value = None


def parseResourceNode():
    pass

def readChild(subj, node, ndoeIDList):
    for child in subj:
        if isProperty(child.tag):
            # 判断有没有nodeID
            nodeID = rdfAttrKey('nodeID')
            if nodeID:
                refNode = findNode(nodeIDList, nodeID)
                parseResourceNode(refNode)
				continue
			
			# 判断有没有child 没有就是纯Literal类型
			subChildLen = len(list(iter(child)))
			if subChildLen == 0:
				res = Resource()
				if hasRdfAttr(child, 'datatype'):
					res.datatype = child.attrib[rdfAttrKey('datatype')]
					res.text = child.text
				# 剩下的，只要不是rdf 开头或者 rdfs开头的都是属性
				for attrKey, attrValue in child.attrib:
					if not attrKey.startswith(ns['rdf']) and not attrKey.startswith(ns['rdfs']) and attrKey != 'xml:lang':
						res.attrKey = attrValue
				tagKey = child.tag
				lang = child.attrib['xml:lang']
				if lang is not None:
					tagKey += ':' + lang
				node.propDict[tagKey] = res
			# 判断有没有parseType
            parseType = rdfAttrKey('parseType')
			if parseType == 'Resource':
				# 剩下的都是直接当成非rdf的属性
				pass
			elif parseType == 'Literal':
				# 剩下的都是直接当成字面量
				pass
			else:
				for level3_child in cild:
					parseResourceNode(level3_child)
        else:
            raise JenaException('child element must be a property')
        resource = rdfAttrKey('resource')
        if hasRdfAttr(child, resource) and resource is not None:
            node.addProperty(child.tag, resource)
        else:
            pass

def isProperty(tag):
    key1 = '\{{}\}'.format(ns['rdf'])
    key2 = '\{{}\}'.format(ns['rdf'])
    if tag.startswith(key1) or tag.startswith(key2):
        return False
    return True

if __name__ == '__main__':
    try:
        import xml.etree.cElementTree as ET
    except ImportError:
        import xml.etree.ElementTree as ET

    nodeList = []
    tree = ET.parse('country.xml')
    # <xml.etree.ElementTree.ElementTree object at 0x00000230D5DDF1C0>
    root = tree.getroot()
    # <Element 'data' at 0x0000021AE8F79540>  type:<class 'xml.etree.ElementTree.Element'>
    #print(root.tag, root.attrib, root.text, root.tail)
    ele = root.find("rdf:Description")
    #print('ele', ele)

    for attr in root:
        print('attr', attr)

    descs = pickDescription(root)
    print('li', descs)

    nodeIDList = []

    for desc in descs:
        if hasRdfAttr('nodeID'):
            ndoeIDList.append(desc)

    for desc in descs:
        print(desc)
        id = None
        node = None
        about = None
        if hasRdfAttr(desc, 'nodeID'):
            nodeID = desc.attrib[rdfAttrKey('nodeID')]
            refNode = findNode(descs, nodeID)
            # subj = refNode
            if refNode is not None:
                node = Node()
                id = refNode.attrib[rdfAttrKey('ID')]
                about = refNode.attrib[rdfAttrKey('about')]
            else:
                raise JenaException('node is illegal nodeID: {}'.format(nodeID))
        else:
            id = desc.attrib[rdfAttrKey('ID')]
            if id:
                node = Node()
                about = desc.attrib[rdfAttrKey('about')]
        if node:
            if id is not None:
                node.id = id
            if about is not None:
                node.about = about

            nodeList.append(node)

    for sub in root:
        print('sub', sub.tag, sub.attrib)
        #for subkey in sub.items():
            #print('subkey',subkey)
        #li = pickDescription(sub)
        #print('li', li)
        #for subsub in sub:
            #print('subsub', subsub)

    #print(root[0])

    # ite = root.iter()
    # for it in ite:
    #     print(it)

    # itetext = root.itertext()
    # for itt in itetext:
    #     print(itt)
    #print('ID', ele.get('ID'))
